﻿using Business.Service;
using Model;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using NPOI.HSSF.UserModel;
using System.Collections;

namespace MvcAppWeb.Controllers
{
    public class DeliveryBoxController : BaseDataController
    {
        //
        // GET: /DeliveryBox/
        public ActionResult DeliveryBox()
        {
            if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            else
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                return View(model);

            }
        }

        ///<summary>
        ///查询箱码
        ///</summary>
        ///<returns></returns>
        public JsonResult InitJsonResult(string dbbcBatchNo, string startDate, string endDate, string seedType)
        {
            string where = "  where 1=1 ";
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;
            if (dbbcBatchNo != "")
            {
                where += " and dbbcBatchNo='" + dbbcBatchNo + "'";
            }
            if (startDate != "" && endDate != "")
            {
                where += " and CREATETIME BETWEEN  to_date('" + startDate + "','yyyy-MM-dd') AND to_date('" + endDate + " 23:59:59 ','yyyy-mm-dd hh24:mi:ss')";
            }
            if (seedType != "0" && seedType != "")
            {
                where += " and lookupid=" + seedType + "";
            }

            var retData = new object();
            BDeliveryBox db = new BDeliveryBox();
            retData = db.GetDeliveryBoxBarCodeList(page, rows, out total, where).ToList();
            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", total);
            json.Add("rows", retData);
            return Json(json);
        }

        ///<summary>
        ///查询箱码
        ///</summary>
        ///<returns></returns>
        public JsonResult GetDeliveryBoxType()
        {
            BDeliveryBox db = new BDeliveryBox();
            var retData = new object();
            retData = db.GetDeliveryBoxType("DELIVERYBOX").ToList();//获取规则
            return Json(retData);
        }


        /// <summary>
        /// 生成箱码
        /// </summary>
        /// <param name="BarCodeNumber"></param>
        /// <returns></returns>
        public string GetLmDeliveryBox(string BarCodeNumber, string seedType)
        {
            string sjson = string.Empty;
            List<LmDeliveryBoxBarCode> lmDeliveryBoxBarCodeList = new List<LmDeliveryBoxBarCode>();
            BDeliveryBox db = new BDeliveryBox();
            try
            {
                AppUserList model = (AppUserList)Session["UserInfo"];

                List<LmSeed> lmSeedlist = db.GetlmSeedList(seedType.Trim().ToString()).ToList();//获取规则
                if (lmSeedlist != null && lmSeedlist.Count > 0)
                {
                    if (lmSeedlist[0].ISRANDOM == "Y")//启用随机数
                    {

                        int total = 0;
                        List<LmDeliveryBoxBarCode> list = db.GetDeliveryBoxBarCodeList(1, 100000, out total, "").ToList();
                        string batchNo = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString(); ;

                        int dbbcLength = lmSeedlist[0].SEEDLENGTH - (lmSeedlist[0].SEEDPREFIX.Length);
                        string[] numbers = getNum(Convert.ToInt32(BarCodeNumber), 1, lmSeedlist[0].SEEDPREFIX, list, dbbcLength, lmSeedlist[0].SUFFIXLENGTH);
                        for (int i = 0; i < numbers.Length; i++)
                        {
                            LmDeliveryBoxBarCode lb = new LmDeliveryBoxBarCode();
                            lb.DBBCBATCHNO = batchNo.ToString();
                            lb.DBBCCODE = numbers[i].ToString();
                            lb.CREATETIME = DateTime.Now.ToString();
                            lb.OPRNO = model.USERNAME;
                            lb.STATUS = "1";
                            lb.LOOKUPID = seedType;
                            lmDeliveryBoxBarCodeList.Add(lb);
                        }
                        if (lmDeliveryBoxBarCodeList.Count > 0)
                        {
                            bool b = db.AddLmDeliveryBoxBarCodeInfo(lmDeliveryBoxBarCodeList);
                            sjson = "{success:true,msg:'" + batchNo + "'}";
                        }
                    }
                    else//非随机生成
                    {
                        LmSeed ls = new LmSeed();
                        int total = 0;
                        List<LmDeliveryBoxBarCode> list = db.GetDeliveryBoxBarCodeList(1, 100000, out total, "").ToList();

                        string batchNo = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString(); ;
                        ls.SEEDID = lmSeedlist[0].SEEDID;
                        ls.SEEDNUMBER = Convert.ToInt32(BarCodeNumber);
                        int dbbcLength = lmSeedlist[0].SEEDLENGTH - (lmSeedlist[0].SEEDPREFIX.Length);
                        int result = db.UpdateLmSeed(ls);
                        if (result > 0)
                        {
                            for (int i = 1; i < (ls.SEEDNUMBER + 1); i++)
                            {
                                LmDeliveryBoxBarCode lb = new LmDeliveryBoxBarCode();
                                lb.DBBCBATCHNO = batchNo.ToString();
                                lb.DBBCCODE = GetDbbcCode(dbbcLength, lmSeedlist[0].SEEDNUMBER + i, lmSeedlist[0].SEEDPREFIX);
                                lb.CREATETIME = DateTime.Now.ToString();
                                lb.OPRNO = model.USERNAME;
                                lb.STATUS = "1";
                                lb.LOOKUPID = seedType;
                                lmDeliveryBoxBarCodeList.Add(lb);
                            }
                            if (lmDeliveryBoxBarCodeList.Count > 0)
                            {
                                bool b = db.AddLmDeliveryBoxBarCodeInfo(lmDeliveryBoxBarCodeList);
                                if (b)
                                {
                                    sjson = "{success:true,msg:'" + batchNo + "'}";
                                }
                                else
                                {
                                    sjson = "{success:false,msg:'生成失败！}";
                                }

                            }
                        }
                    }
                }
                else
                {
                    sjson = "{success:false,msg:'请先添加条码规则.'}";
                }
            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
            }

            return sjson;
        }



        /// <summary>
        /// 导出条码
        /// </summary>
        /// <param name="dbbcBatchNo"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public FileResult ExporterExcel(string dbbcBatchNo, string startDate, string endDate)
        {
            int total = 0;
            string where = "  where 1=1 ";

            if (dbbcBatchNo != "")
            {
                where += " and dbbcBatchNo='" + dbbcBatchNo + "'";
            }
            if (startDate != "" && endDate != "")
            {
                where += " and CREATETIME BETWEEN  to_date('" + startDate + "','yyyy-MM-dd') AND to_date('" + endDate + " 23:59:59 ','yyyy-mm-dd hh24:mi:ss')";
            }
            BDeliveryBox db = new BDeliveryBox();
            List<LmDeliveryBoxBarCode> list = db.GetDeliveryBoxBarCodeList(1, 20000, out total, where).ToList();

            //创建Excel文件的对象
            HSSFWorkbook book = new HSSFWorkbook();
            //添加一个sheet
            ISheet addr = book.CreateSheet("Sheet1");

            for (int i = 0; i < list.Count + 1; i++)
            {
                addr.CreateRow(i);
                addr.GetRow(i).Height = 400;
                if (i == 0)
                {
                    addr.GetRow(0).CreateCell(0).SetCellValue("配送箱号");
                }
                else
                {
                    addr.GetRow(i).CreateCell(0).SetCellValue(list[i - 1].DBBCCODE);
                }
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", NewTimeStamp("配送箱号"));

        }

        /// <summary>
        /// 补足条码长度
        /// </summary>
        /// <param name="dbbcLength"></param>
        /// <param name="seedNumber"></param>
        /// <param name="seedPrefix"></param>
        /// <returns></returns>
        public string GetDbbcCode(int dbbcLength, int seedNumber, string seedPrefix)
        {
            string bbcCode = "";
            if (true)
            {
                bbcCode = seedPrefix + seedNumber.ToString().PadLeft(dbbcLength, '0');
            }
            return bbcCode;

        }



        /// <summary> 
        /// 产生无重复随机数 
        /// </summary> 
        /// <param name="num">个数</param> 
        /// <param name="minValue">最小数</param> 
        /// <param name="maxValue">最大数</param> 
        /// <returns>数组</returns> 
        public string[] getNum(int num, int minValue, string seedPrefix, List<LmDeliveryBoxBarCode> list, int dbbcLength, int RandomNumberLength)
        {
            string number = "";
            if (RandomNumberLength > 0)
            {
                for (int i = 0; i < RandomNumberLength; i++)
                {
                    number = number + "9";
                }
            }
            Random ra = new Random(unchecked((int)DateTime.Now.Ticks));
            int[] arrNum = new int[num];//注意:数组中各元素的初始值是0,当0在取值范围内时要另处理 
            string[] bbcCodes = new string[num];
            int tmp = 0;
            for (int i = 0; i < num; i++)
            {
                tmp = getRandomNum(tmp, minValue, Convert.ToInt32(number), ra);//取出值赋到数组中 
                string bbcCode = seedPrefix + tmp.ToString().PadLeft(dbbcLength, '0');

                if (Array.IndexOf(arrNum, tmp) < 0)//判断是否存在,不存在的话元素tmp的索引应为-1 
                {

                    if (list != null && list.Count > 0)
                    {
                        var datass = list.Where(s => s.DBBCCODE == Convert.ToString(bbcCode)).ToList();
                        if (datass.Count > 0)//如果有重复的就重新生成
                        {
                            i = i - 1;
                        }
                        else
                        {
                            arrNum[i] = tmp;
                            bbcCodes[i] = bbcCode;
                        }
                    }
                    else
                    {
                        arrNum[i] = tmp;
                        bbcCodes[i] = bbcCode;
                    }
                }
                else
                {
                    i = i - 1;
                }


            }
            return bbcCodes;
        }
        public int getRandomNum(int tmp, int minValue, int maxValue, Random ra)
        {
            tmp = ra.Next(minValue, maxValue);
            return tmp;
        }

    }
}
